package org.cuit.seon;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者
 */
class ProductDemo implements Runnable {
    //工作队列
    private final BlockingQueue<Runnable> work;
    private volatile Boolean flag = true;
    AtomicInteger atomicInteger = new AtomicInteger();

    public ProductDemo(BlockingQueue<Runnable> work) {
        this.work = work;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程生产者开始运行=====");

        try {
            while (flag) {
                int count = atomicInteger.incrementAndGet();
                String currentThreadName = Thread.currentThread().getName();
                //生产者往阻塞队列中放数据
                work.put(() -> System.out.println(currentThreadName + "线程的第" + count + "次提交任务被" + Thread.currentThread().getName() + "执行"));
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "线程生产者运行结束=====");
        }
    }

    public void stop() {
        flag = false;
    }

}

/**
 * 消费者
 */
class ConsumerDemo implements Runnable {
    //工作队列
    private final BlockingQueue<Runnable> work;

    public ConsumerDemo(BlockingQueue<Runnable> work) {
        this.work = work;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "消费者开始===========");
        try {
            while (true) {
                System.out.println(Thread.currentThread().getName() + "等待任务获取");
                //生产者从阻塞队列中获取数据
                Runnable task = work.take();
                System.out.println(Thread.currentThread().getName() + "任务获取完毕，消费者线城池开始执行任务，结果为");
                task.run();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "消费者结束===========");
        }
    }
}

public class QueueExecutePlaner {
    public static void main(String[] args) {
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
        ProductDemo productDemo = new ProductDemo(workQueue);
        ConsumerDemo consumerDemo = new ConsumerDemo(workQueue);
        Thread producer = new Thread(productDemo);
        Thread consumer = new Thread(consumerDemo);
        producer.start();
        consumer.start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        productDemo.stop();
    }
}
